package com.pinyougou.manager.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.pinyougou.entity.PageResult;
import com.pinyougou.entity.Result;
import com.pinyougou.pojo.Brand;
import com.pinyougou.sellergoods.service.BrandService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("brand")
public class BrandController {
    @Reference
    private BrandService brandService;

    @GetMapping("{id}")
    public Brand detail(@PathVariable Integer id) {
        Brand brand = brandService.findById(id);
        return brand;
    }

    @GetMapping("list/{pageNum}/{pageSize}")
    public PageResult<Brand> list(@PathVariable Integer pageNum,
                                  @PathVariable Integer pageSize) {
        PageResult<Brand> pageResult = brandService.findByPage(pageNum, pageSize);
        return pageResult;
    }

    @GetMapping("list")
    public List<Brand> list() {
        List<Brand> brandList = brandService.findAll();
        return brandList;
    }
    @GetMapping("list/options")
    public List<Map> selectOptions(){
        List<Map> options=brandService.selectOptions();
        return options;
    }
    @PutMapping("search/{pageNum}/{pageSize}")
    public PageResult<Brand> search(@RequestBody(required = false) Brand brand, @PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        PageResult<Brand> pageResult = brandService.findByPage(brand, pageNum, pageSize);
        return pageResult;
    }

    @PostMapping
    public Result add(@RequestBody Brand brand) {
        try {
            brandService.save(brand);
            return new Result(true, "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "添加失败");
        }
    }

    @PutMapping
    public Result update(@RequestBody Brand brand) {
        try {
            brandService.update(brand);
            return new Result(true, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "更新失败");
        }
    }

    @DeleteMapping("delete")
    public Result delete(Integer[] ids) {
        if (ids == null || ids.length < 1)
            return new Result(false, "必须选中一个");
        try {
            brandService.delete(ids);
            return new Result(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
    }

}
